import Honey from '../../utils/honey';
import Event from '../../utils/event'

const app = getApp();
const honey = new Honey();
const event = new Event();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    broadcastList: [],
    bulletinList: [],
    organization: {},
    marketing: {},
    teseList: [],
    keyword: '',
    searchFocus: false,
    user: "",
    bindGetUserInfoshow: false,
    getPhoneNumbershow: false,
    parent_id: "",
    redpacketshow: false,
    redpacketNextshow: false,
    redpacketurl: '',
    healthstatus: false,
    advertisingshow: false,
    redpacketNum: "",
    // isfirst: true,
    aniationArray: {
      first: '',
      second: '',
      third: '',
      fourth: '',
      fifth: ''
    },
    getPhoneSuccess: true,
    phoneUntying: false, //手机解绑框
    message: '', //手机已存在绑定账号提示信息
    lock: true, //授权加锁，防止连续点击
    rushGoods: [], //抢购商品列表
    recommendGoods: [], //推荐商品列表
    canToMall: true, //
    scrollHeight: 100000,
    system: app.globalData.system,
    animationText:'',//新用户首次进入动画文字
    reportIdcardShow:false,//自己查询模态框
    idcard:''//报告自己查询身份证号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideTabBar({})
    
    var that = this;
    if(options.show==""){
      that.setData({
        bindGetUserInfoshow:true,
      })
    }

    that.setData({
      broadcastList: wx.getStorageSync('broadcastList') || [],
      organization: wx.getStorageSync('organization') || [],
      marketing: wx.getStorageSync('marketing') || [],
    })

    var scene = decodeURIComponent(options.scene);
    if (options.check_code) {
      wx.setStorageSync('checkCode', options.check_code)
    }
    if (wx.getStorageSync('checkCode') && !wx.getStorageSync('user')) {
      this.setData({
        bindGetUserInfoshow: true,
      })
    }
    if (options.code) {
      const parent_id = options.code;
      that.setData({
        parent_id: parent_id
      })
    }
    if (scene) {
      let infoArr = [];
      infoArr = scene.split(',');
      if (infoArr[0].split('=')[0] == 'check_code') {
        wx.setStorageSync('checkCode', infoArr[0].split('=')[1])
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    const that = this;
    event.on('getUserInfo', 'myAccount', function(data) {
      that.setData({
        user: data
      })
    })

    setInterval(() => {
      event.emit('refreshUserInfo', 'userInfo');
    }, 30000)

    if(wx.getStorageSync('user')){
      that.adviceShow();
    }
    that.getPagesConfig();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
        wx.login({
          success: res => {
            honey.post({
              alias: 'minSessionKey',
              data: {
                code: res.code
              },
              success: function(res) {
                wx.setStorageSync('sessionKey', res.data.data.result.session_key)
              }
            })
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
          }
        })
    that.setData({
      canToMall: true,
    })
   
      that.getHomeData();
      


    const user = wx.getStorageSync('user');

    that.setData({
      user,
    })
    if (that.data.user != "") {
      that.setData({
        bindGetUserInfoshow: false,
      })
    }
    // if (that.data.phone == "") {
    //   that.setData({
    //     getPhoneNumbershow: true,
    //   })
    // } else {
    //   that.setData({
    //     getPhoneNumbershow: false,
    //   })
    //   that.turnToReferrer();
    // }


    // that.showAnimationMask();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      canToMall: false,
    })
    this.healthHide();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    wx.showLoading({
      title: '即将前往商城',
    })
    setTimeout(() => {
      wx.hideLoading();
      wx.navigateTo({
        url: '/pages/mall/newindex?keyword=',
      })
    }, 1500)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    const that = this;
    return {
      title: `平台烧钱啦～点击领取大红包！`,
      path: `/pages/index/index?check_code=${that.data.user.check_code}`,
      imageUrl: '/res/activity1.jpeg'
    }
  },
  inputKeyword: function(e) {
    const that = this;
    that.setData({
      keyword: e.detail.value
    })
  },
  toSearch: function() {
    const that = this;
    wx.navigateTo({
      url: '/pages/search/index?keyword=' + that.data.keyword,
    })
  },
  toChangeBtn: function() {
    const that = this;
    that.setData({
      searchFocus: true
    })
  },
  toRestoreBtn: function() {
    const that = this;
    that.setData({
      searchFocus: false
    })
  },
  showbgcx: function() {
    const that = this;
    wx.previewImage({
      current: 'https://xmjkws.com/aaa/newbgcx.jpg', // 当前显示图片的http链接
      urls: ['https://xmjkws.com/aaa/newbgcx.jpg'] // 需要预览的图片http链接列表
    })
  },
  showQrcode: function() {
    const that = this;
    if (that.data.user == false) {
      wx.showToast({
        title: '请先登录！',
        image: "../../res/images/icon-shibai.png"
      })
      return;
    }
    wx.previewImage({
      current: 'https://xmjkws.com//phalapi/public/qr_img/qrcode_' + that.data.user.id + '.jpg', // 当前显示图片的http链接
      urls: ['https://xmjkws.com//phalapi/public/qr_img/qrcode_' + that.data.user.id + '.jpg'] // 需要预览的图片http链接列表
    })
  },

  //微信授权登陆接口
  bindGetUserInfo(e) {
    const that = this;
    if (that.data.lock) {
      that.setData({
        lock: false,
      })
      if (e.detail.errMsg == "getUserInfo:ok") {
        honey.post({
          alias: 'minLogin',
          data: {
            share_code: wx.getStorageSync('checkCode'),
            encrypt: e.detail.encryptedData,
            iv: e.detail.iv,
            session_key: wx.getStorageSync('sessionKey'),
          },
          success(res) {
            wx.setStorageSync('user', res.data.data.userInfo);
            if (res.data.data.userInfo.mobile) {
              wx.setStorageSync('phone', res.data.data.userInfo.mobile)
            }
            that.setData({
              bindGetUserInfoshow: false,
              user: res.data.data.userInfo,
            })
            that.getHomeData();

            if (res.data.data.git > 0) {
              that.setData({
                redpacketshow: true,
                redpacketNum: res.data.data.git,
                redpacketurl: res.data.data.redpack_img
              })
              that.turnToReferrer();
              that.showAnimationMask();
            }
            wx.removeStorageSync('checkCode');
            
          },
          complete: function() {
            that.setData({
              lock: true,
            })
          }
        })
      }
    }

  },

  //手机授权接口
  getPhoneNumber: function(e) {
    const that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      this.setData({
        getPhoneSuccess: true
      })
      const phone = e.detail;
      honey.post({
        alias: 'bindUserPhone',
        data: {
          encrypt: phone.encryptedData,
          iv: phone.iv,
          session_key: wx.getStorageSync('sessionKey')
        },
        success: function(res) {
          if (res.data.data.had_bind == 1) {
            that.setData({
              phoneUntying: true,
              unPhone: res.data.data.mobile,
              message: res.data.message
            })
          } else {
            wx.setStorageSync('phone', res.data.data.userInfo.mobile);
            const value = res.data.data.userInfo;
            that.setData({
              getPhoneNumbershow: false,
            })
            that.redpacketHide();
          }
          event.emit('refreshUserInfo', 'userInfo');
        }
      })

    } else {
      that.setData({
        getPhoneSuccess: false,
        getPhoneNumbershow: false,
      })
    }
  },

  healthmoneygo: function() {
    const that = this;
    that.setData({
      redpacketshow: false,
    })
    wx.navigateTo({
      url: '/pages/mine/myFund',
    })
  },

  healthShow: function() {
    const that = this;
    that.setData({
      healthstatus: true
    })
  },
  healthHide: function() {
    const that = this;
    that.setData({
      healthstatus: false
    })
  },

  advertisinggo: function(e) {
    const that = this;
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.id;
    if (type == "8") {
      wx.navigateTo({
        url: '/pages/article/lunbo?id=' + id,
      })
    }
    if (type == "2") {
      wx.navigateTo({
        url: '/pages/combo/newdetail?id=' + id,
      })
    }
    if (type == "7") {
      wx.navigateTo({
        url: '/pages/organization/newindex?id=' + id,
      })
    }
    if (type == "9") {
      wx.navigateTo({
        url: '/pages/mine/superWelfare?id=' + id,
      })
    }
    if (type == "4") {
      wx.navigateTo({
        url: id,
      })
    }
    that.setData({
      advertisingshow: false
    })
  },
  advertisingHide: function() {
    const that = this;
    that.setData({
      advertisingshow: false
    })
  },
  redpacketHide: function() {
    const that = this;
    that.setData({
      redpacketNextshow: false,
    })
    // wx.showTabBar({
    //   animation: true
    // });
    if (wx.getStorageSync('pagesUrl')) {
      const url = wx.getStorageSync('pagesUrl');
      wx.removeStorageSync('pagesUrl');
      if (wx.getStorageSync('isTab')) {
        wx.removeStorageSync('isTab');
        wx.switchTab({
          url: url,
        })
      } else {
        wx.navigateTo({
          url: url,
        })
      }
    }
  },

  //通过分享进入新用户注册完毕回到原分享页面
  turnToReferrer: function() {
    if (wx.getStorageSync('pagesUrl')) {
      const url = wx.getStorageSync('pagesUrl');
      wx.removeStorageSync('pagesUrl');

      if (wx.getStorageSync('isTab')) {
        wx.removeStorageSync('isTab');
        wx.switchTab({
          url: url,
        })
      } else {
        wx.navigateTo({
          url: url,
        })
      }
    }else{
      console.log(111222);
      wx.navigateBack({
        delta: 1,
      });
    }
  },

  //跳转健康商城
  onClickSwitch: function() {
    wx.navigateTo({
      url: '/pages/mall/newindex?keyword=',
    })
  },

  //播放动画事件
  showAnimationMask: function() {
    const that = this;
    let animationArray = that.data.aniationArray;
    animationArray.first = 'animated animate-mask-item-show fadeInUp';
    setTimeout(() => {
      that.setData({
        aniationArray: animationArray
      })
      animationArray.second = 'animated animate-mask-item-show fadeInUp';
      setTimeout(() => {
        that.setData({
          aniationArray: animationArray
        })
        animationArray.third = 'animated animate-mask-item-show fadeInUp';
        setTimeout(() => {
          that.setData({
            aniationArray: animationArray
          })
          animationArray.fourth = 'animated animate-mask-item-show rubberBand';
          animationArray.fifth = 'animated animate-mask-item-show rubberBand';

          setTimeout(() => {
            that.setData({
              aniationArray: animationArray
            })
            setTimeout(() => {
              that.setData({
                aniationArray: animationArray
              })
            }, that.data.animationTime.words_speed * 1000)
          }, that.data.animationTime.img_speed * 1000)
        }, that.data.animationTime.words_speed * 1000)
      }, that.data.animationTime.words_speed * 1000)
    }, that.data.animationTime.start_speed * 1000)

  },

  //点击打开红包
  toActivePage: function() {
    const that = this;
    if (that.data.aniationArray.fourth != '') {
      // wx.showTabBar({
      //   aniamtion: true
      // });
      that.setData({
        redpacketshow: false,
        redpacketNextshow: true
      })
    }
   
    that.adviceShow();
  },
  getPhoneAgain: function() {
    wx.showToast({
      title: '健康分享平台需要使用您的手机号，方便绑定您的信息，请允许',
      icon: 'none',
      duration: 2000,
      complete: () => {
        this.setData({
          getPhoneNumbershow: true
        })
      }
    })

  },
  //查询报告
  toreport: function() {
    const that = this;
    if (!wx.getStorageSync('user') || !that.data.user.mobile) {
      that.setData({
        getPhoneNumbershow: true,
      })
      return;
    }
    wx.showActionSheet({
      itemList: ['自己查询', '帮他人查询'],
      success(res) {
        if (res.tapIndex == 0) {
          that.setData({
            reportIdcardShow:true
          })
          
        } else if (res.tapIndex == 1) {
          wx.navigateTo({
            url: '/pages/register/register',
          })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  //首页数据接口
  getHomeData: function() {
    const that = this;
    honey.post({
      alias: 'homeHomeData',
      success: function(res) {
        if (res.data.status == 1) {
          wx.setStorageSync('broadcastList', res.data.data.bannerList);
          wx.setStorageSync('organization', res.data.data.advBottom);
          wx.setStorageSync('marketing', res.data.data.advPopup[0]);
          that.setData({
            broadcastList: res.data.data.bannerList,
            organization: res.data.data.advBottom,
            marketing: res.data.data.advPopup[0],
            teseList: res.data.data.homeMenu,
            bulletinList: res.data.data.notice,
            rushGoods: res.data.data.rushGoods.list,
            recommendGoods: res.data.data.recommendGoods.list,
          })
        }
      }
    })
  },

  //隐藏手机授权窗口
  clearPhonemask: function() {
    const that = this;
    that.setData({
      getPhoneNumbershow: false,
    })
  },

  //隐藏手机解绑窗口
  clearUntyingmask: function() {
    const that = this;
    that.setData({
      phoneUntying: false,
    })
  },

  //解绑手机号
  untyingPhone: function() {
    const that = this;
    honey.post({
      alias: 'unbindUserPhone',
      data: {
        mobile: that.data.unPhone
      },
      success: function(res) {
        wx.showToast({
          title: '绑定成功',
          icon: 'none'
        })
        wx.setStorageSync('phone', that.data.unPhone);
        that.setData({
          getPhoneNumbershow: false,
          phoneUntying: false,
        })
      }
    })
  },

  clearUntyingPhone: function() {
    that.setData({
      phoneUntying: false,
    })
  },
  calcScorllHeight: function() {
    const that = this;
    const query = wx.createSelectorQuery();
    query.select('#homeScroll').boundingClientRect()
    query.exec(function(res) {
      if (res[0]) {
        that.setData({
          scrollHeight: res[0].height
        })
      }
    })
  },

  //首页越界跳转商城页
  homeScrollHandle: function(event) {
    const that = this;
    if (event.detail.scrollTop + that.data.scrollHeight - event.detail.scrollHeight > 50) {
      if (that.data.canToMall) {
        wx.navigateTo({
          url: '/pages/mall/newindex?keyword=',
        })
      }
    }
  },

  //新用户初次进入动画文字信息及动画时间
  getPagesConfig:function(){
  const that=this;
  honey.post({
    alias:'getPagesConfig',
    success(res){
      that.setData({
        animationText: res.data.data.pagesConfig.index.dialogue,
        animationTime: res.data.data.pagesConfig.index
      })
    }
  });
  },

  //关闭微信授权框
  clearUserShow:function(){
    this.setData({
      bindGetUserInfoshow:false
    })
  },

  //身份证监听
  idcard(e){
  const that=this;
  that.setData({
    idcard:e.detail.value,
  })
  },

  //查询报告
  toselect(){
    const that=this;
      wx.navigateTo({
        url: '/pages/report/index?idcard=' + that.data.idcard,
      })
  },

  //关闭身份证查询验证模态框
  clearIdcard(){
    const that=this;
    that.setData({
      reportIdcardShow:false,
    })
  },

  //广告显示
  adviceShow(){
    const that=this;
    if (new Date().getTime() >= wx.getStorageSync('time') + 86400000) {
      that.setData({
        advertisingshow: true,
      })
      wx.setStorageSync('time', new Date().getTime())
    }
  }

})